import React, { Component } from 'react'
import { View, Text, OpenData, ScrollView, Image, Input } from '@tarojs/components'
import { AtActivityIndicator, AtTabBar, AtActionSheet, AtActionSheetItem, AtFloatLayout, AtButton } from 'taro-ui'
import Taro, { getCurrentInstance } from '@tarojs/taro'
import './index.scss'
import { IMAGES } from '../../uilts/images'
import { GetT } from '../../uilts/textLib'
import { DeviceList } from '../../serverless/deviceList'
import { WeMqttApi } from '../../serverless/weMqttApi'

let T = GetT()

enum STEP {
  WAIT_ACC_LED,
  GETTING_SSID_LIST,
  WAIT_SELECT_LED_WIFI,
  LED_ACC_SUCC,
}

interface SsidList {
  ssid: string;
  bssid: string;
  rssi: number;
  authmode: string;
}

export default class Index extends React.Component {

  state = {
    mode: '',
    modeId: '',
    groupId: '',
    step: STEP.WAIT_ACC_LED,
    ssidList: [] as SsidList[],
    atActionSheetOpen: false,
    atFloatLayoutOpen: false,
    ledinfo: {},
    SSID: '',
    PWD: '',
    finalCountdown: 3
  }

  private neetLedInfo: Boolean = false

  onReady() {
    try {
      const a = Taro.getCurrentInstance();
      if (a.router) {
        const { mode, _id, groupId } = a.router.params
        this.setState({ mode: mode, modeId: _id, groupId: groupId })
        this.requestLEDInfo()
      } else
        throw new Error('页面传入信息不全');
    } catch (error) {
      Taro.showModal({
        title: '提示',
        content: error.message,
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            Taro.redirectTo({ url: "/pages/index/index" })
          }
        }
      })
    }
  }

  componentWillUnmount() {
    this.neetLedInfo = true
  }

  /** 请求LED的信息，包含通讯码 */
  requestLEDInfo() {
    Taro.request({
      url: 'http://192.168.4.1:14593/demoks/info',
      data: {},
      timeout: 3000,
      header: {
        'content-type': 'application/json',
        'x-access-token': 'TdVmqLfSXsUPkCDNYygsMcj8mgaBuYLD'
      },
      success: (res) => {
        this.neetLedInfo = true
        console.info(res.data)
        setTimeout(() => {
          this.setState({
            ledinfo: res.data,
            step: STEP.GETTING_SSID_LIST
          }, () => {
            this.requestLedSsidList()
          })
        }, 2000);
      },
      fail: (_err) => {
        // console.log(err);
        setTimeout(() => {
          if (!this.neetLedInfo)
            this.requestLEDInfo()
        }, 2000);
      }
    })
  }

  /** 请求WIFI模块搜索到SSID列表 */
  requestLedSsidList() {
    Taro.request({
      url: 'http://192.168.4.1:14593/wifi/ssid',
      data: {},
      timeout: 30000,
      header: {
        'content-type': 'application/json',
        'x-access-token': 'TdVmqLfSXsUPkCDNYygsMcj8mgaBuYLD'
      },
      success: (res) => {
        console.info(res.data)
        this.setState({
          ssidList: res.data.list,
          step: STEP.WAIT_SELECT_LED_WIFI,
          atActionSheetOpen: true
        })
      },
      fail: (err) => {
        console.log(err);

      }
    })
  }

  /** 告诉WIFI模块需要连接的SSID,以及它的密码 */
  requestLedDistribution() {
    const { SSID, PWD } = this.state
    Taro.showLoading({
      title: '连接中',
    })
    Taro.request({
      url: 'http://192.168.4.1:14593/wifi/distribution',
      method: 'POST',
      data: {
        passwd: PWD,
        ssid: SSID,
      },
      timeout: 30000,
      header: {
        'content-type': 'application/json',
        'x-access-token': 'TdVmqLfSXsUPkCDNYygsMcj8mgaBuYLD'
      },
      success: (res) => {
        console.info(res.data)
        const { code, msg } = res.data
        if (code === 0) {
          // 连接成功
          this.setState({
            step: STEP.LED_ACC_SUCC,
            atActionSheetOpen: false,
            atFloatLayoutOpen: false,
            finalCountdown: 4, // 倒计时时间，主要等待设备热点主动断开
          }, () => {
            // 开始倒计时
            this.startCountdown()
          })
        } else {
          console.error(msg)
          Taro.showModal({
            title: 'WIFI连接失败',
            content: '请检查WIFI密码是否正确',
            showCancel: false
          })
        }
      },
      fail: (err) => {
        console.log(err);
      },
      complete: () => {
        Taro.hideLoading()
      }
    })
  }

  startCountdown() {
    const { finalCountdown } = this.state
    if (finalCountdown > 0) {
      this.setState({
        finalCountdown: finalCountdown - 1
      }, () => {
        setTimeout(() => {
          this.startCountdown()
        }, 1000);
      })
    }
  }

  /** 绑定当前设备 */
  async onAddDevice() {
    const { mode, modeId, ledinfo, SSID, groupId } = this.state
    console.log({
      mode, modeId, ledinfo, SSID
    });

    try {
      Taro.showLoading({
        title: '绑定中...',
      })
      // 保存数据到云数据库
      const b = await DeviceList.CreateDevice(
        // 取通讯码前8位做设备的临时名称
        `${ledinfo['publicKey']}`.substr(0, 8),
        modeId,
        groupId,
        ledinfo,
      );
      console.log(b._id);
      // 关闭所有页面，返回主页并传递参数告知主页来自绑定设备页面，还有刚刚添加的设备ID
      Taro.reLaunch({
        url: `/pages/index/index?from=bind_device&_id=${b._id}`
      })
    } catch (error) {
      Taro.showModal({
        title: '绑定失败',
        content: error.message,
        showCancel: false,
        success: function (res) {
          if (res.confirm) {

          }
        }
      })
    }
    Taro.hideLoading()
  }

  modeLononled() {
    const { step, atActionSheetOpen, ssidList, atFloatLayoutOpen, SSID, finalCountdown } = this.state
    const arr = ssidList.map((x, i) => {
      return <AtActionSheetItem key={i} onClick={() => {
        this.setState({
          atActionSheetOpen: false,
          atFloatLayoutOpen: true,
          SSID: x.ssid,
          PWD: ''
        })
      }}>{x.ssid || x.bssid}</AtActionSheetItem>
    })
    return <View className='modeLononled'>
      {/* 用户指引 1 */}
      <View className='at-row'>
        <View className='at-col at-col-12 number center-horizontally'>
          <View>①</View>
        </View>
      </View>
      <View className='at-row'>
        <View className='at-col at-col-4 number center-horizontally'>
          <Image className='image' src={IMAGES.shangdian}></Image>
        </View>
        <View className='at-col at-col-8 center-horizontally justify-content-flex-start'>
          <View>
            <View className='text'>  请给LED灯板重新上电。 </View>
            <View >无连接下热点仅维持3分钟 </View>
          </View>
        </View>
      </View>
      {/* 用户指引 2 */}
      <View className='at-row'>
        <View className='at-col at-col-12 number center-horizontally'>
          <View>②</View>
        </View>
      </View>
      <View className='at-row'>
        <View className='at-col at-col-4 number center-horizontally'>
          <Image className='image wifi' src={IMAGES.wifi}></Image>
        </View>
        <View className='at-col at-col-8 center-horizontally justify-content-flex-start'>
          <View>
            <View className='text' >请手动连接LED的WIFI热点。 </View>
            <View >WIFI-SSID:LononLED </View>
          </View>
        </View>
      </View>
      {/* 用户指引 3 */}
      <View className='at-row'>
        <View className='at-col at-col-12 number center-horizontally'>
          <View>③</View>
        </View>
      </View>
      <View className='at-row'>
        <View className='at-col at-col-4 number center-horizontally'>
          <Image className='image' src={IMAGES.connection}></Image>
        </View>
        <View className='at-col at-col-8 center-horizontally justify-content-flex-start'>
          {step === STEP.WAIT_ACC_LED && <AtActivityIndicator content='等待连接热点...'></AtActivityIndicator>}
          {step === STEP.GETTING_SSID_LIST && <AtActivityIndicator content='正在获取附近的WIFI...'></AtActivityIndicator>}
          {step === STEP.WAIT_SELECT_LED_WIFI && <View className='center-horizontally'>
            <View className='no-neet' onClick={() => {
              this.setState({
                step: STEP.GETTING_SSID_LIST
              }, () => {
                this.requestLedSsidList()
              })
            }}>
              <View className='text1'>没有我要的SSID</View>
              <View className='text2'>点击重新获取</View>
            </View>
          </View>}
          {step === STEP.LED_ACC_SUCC && <View className='center-horizontally'>
            <View>
              <View className='text' >连接成功 </View>
              <View >当前网络:{SSID}</View>
            </View>
          </View>}
        </View>
      </View>
      {/* 用户指引 4 */}
      {step === STEP.LED_ACC_SUCC && <View>
        <View className='at-row'>
          <View className='at-col at-col-12 number center-horizontally'>
            <AtButton type='primary' disabled={finalCountdown > 0} onClick={this.onAddDevice.bind(this)}>{
              finalCountdown <= 0 ? '添加设备' : `等待网络恢复（${finalCountdown}）`
            }</AtButton>
          </View>
        </View>
      </View>}
      {/* 选择WIFI的列表 */}
      <AtActionSheet
        isOpened={atActionSheetOpen}
        cancelText='取消'
        title='点击需要连接的WIFI'
        onClose={() => { this.setState({ atActionSheetOpen: false }) }}
      >
        {arr}
      </AtActionSheet>

      {/* 输入WIFI密码 */}
      <AtFloatLayout isOpened={atFloatLayoutOpen} title="请输入WIFI密码" onClose={() => { this.setState({ atFloatLayoutOpen: false }) }}>
        <View className="pwd-input">
          <View className='at-row'>
            <View className='at-col at-col-4 title'>选择的WIFI:</View>
            <View className='at-col at-col-8'>{SSID}</View>
          </View>
          <View className='at-row'>
            <View className='at-col at-col-4 title'>WIFI密码:</View>
            <View className='at-col at-col-8'>
              <Input password type='text' maxlength={32} placeholder="请输入" onInput={(e) => {
                this.setState({ PWD: e.detail.value })
              }} />
            </View>
          </View>
          <View className='at-row'>
            <View className='at-col at-col-12'>
              <AtButton type='primary' onClick={() => {
                this.requestLedDistribution()
              }}>发送密码</AtButton>
            </View>
          </View>
        </View>
      </AtFloatLayout>
    </View>
  }

  modeLononRELAY() {
    const { step, atActionSheetOpen, ssidList, atFloatLayoutOpen, SSID, finalCountdown } = this.state
    const arr = ssidList.map((x, i) => {
      return <AtActionSheetItem key={i} onClick={() => {
        this.setState({
          atActionSheetOpen: false,
          atFloatLayoutOpen: true,
          SSID: x.ssid,
          PWD: ''
        })
      }}>{x.ssid || x.bssid}</AtActionSheetItem>
    })
    return <View className='modeLononled'>
      {/* 用户指引 1 */}
      <View className='at-row'>
        <View className='at-col at-col-12 number center-horizontally'>
          <View>①</View>
        </View>
      </View>
      <View className='at-row'>
        <View className='at-col at-col-4 number center-horizontally'>
          <Image className='image' src={IMAGES.shangdian}></Image>
        </View>
        <View className='at-col at-col-8 center-horizontally justify-content-flex-start'>
          <View>
            <View className='text'> 请给LononRELAY重新上电。 </View>
            <View >无连接下热点仅维持3分钟 </View>
          </View>
        </View>
      </View>
      {/* 用户指引 2 */}
      <View className='at-row'>
        <View className='at-col at-col-12 number center-horizontally'>
          <View>②</View>
        </View>
      </View>
      <View className='at-row'>
        <View className='at-col at-col-4 number center-horizontally'>
          <Image className='image wifi' src={IMAGES.wifi}></Image>
        </View>
        <View className='at-col at-col-8 center-horizontally justify-content-flex-start'>
          <View>
            <View className='text view-white-space' >请手动连接LononRELAY的WIFI热点。 </View>
            <View >WIFI-SSID:LononRELAY </View>
          </View>
        </View>
      </View>
      {/* 用户指引 3 */}
      <View className='at-row'>
        <View className='at-col at-col-12 number center-horizontally'>
          <View>③</View>
        </View>
      </View>
      <View className='at-row'>
        <View className='at-col at-col-4 number center-horizontally'>
          <Image className='image' src={IMAGES.connection}></Image>
        </View>
        <View className='at-col at-col-8 center-horizontally justify-content-flex-start'>
          {step === STEP.WAIT_ACC_LED && <AtActivityIndicator content='等待连接热点...'></AtActivityIndicator>}
          {step === STEP.GETTING_SSID_LIST && <AtActivityIndicator content='正在获取附近的WIFI...'></AtActivityIndicator>}
          {step === STEP.WAIT_SELECT_LED_WIFI && <View className='center-horizontally'>
            <View className='no-neet' onClick={() => {
              this.setState({
                step: STEP.GETTING_SSID_LIST
              }, () => {
                this.requestLedSsidList()
              })
            }}>
              <View className='text1'>没有我要的SSID</View>
              <View className='text2'>点击重新获取</View>
            </View>
          </View>}
          {step === STEP.LED_ACC_SUCC && <View className='center-horizontally'>
            <View>
              <View className='text' >连接成功 </View>
              <View >当前网络:{SSID}</View>
            </View>
          </View>}
        </View>
      </View>
      {/* 用户指引 4 */}
      {step === STEP.LED_ACC_SUCC && <View>
        <View className='at-row'>
          <View className='at-col at-col-12 number center-horizontally'>
            <AtButton type='primary' disabled={finalCountdown > 0} onClick={this.onAddDevice.bind(this)}>{
              finalCountdown <= 0 ? '添加设备' : `等待网络恢复（${finalCountdown}）`
            }</AtButton>
          </View>
        </View>
      </View>}
      {/* 选择WIFI的列表 */}
      <AtActionSheet
        isOpened={atActionSheetOpen}
        cancelText='取消'
        title='点击需要连接的WIFI'
        onClose={() => { this.setState({ atActionSheetOpen: false }) }}
      >
        {arr}
      </AtActionSheet>

      {/* 输入WIFI密码 */}
      <AtFloatLayout isOpened={atFloatLayoutOpen} title="请输入WIFI密码" onClose={() => { this.setState({ atFloatLayoutOpen: false }) }}>
        <View className="pwd-input">
          <View className='at-row'>
            <View className='at-col at-col-4 title'>选择的WIFI:</View>
            <View className='at-col at-col-8'>{SSID}</View>
          </View>
          <View className='at-row'>
            <View className='at-col at-col-4 title'>WIFI密码:</View>
            <View className='at-col at-col-8'>
              <Input password type='text' maxlength={32} placeholder="请输入" onInput={(e) => {
                this.setState({ PWD: e.detail.value })
              }} />
            </View>
          </View>
          <View className='at-row'>
            <View className='at-col at-col-12'>
              <AtButton type='primary' onClick={() => {
                this.requestLedDistribution()
              }}>发送密码</AtButton>
            </View>
          </View>
        </View>
      </AtFloatLayout>
    </View>
  }


  render() {
    const { mode } = this.state
    return (
      <View className='index guide'>
        {mode === 'lononled' && this.modeLononled()}
        {mode === 'lononRELAY' && this.modeLononRELAY()}
      </View>
    )
  }
}
